﻿using Microsoft.AspNetCore.Mvc;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Services.EntityServices.SchduleTasks;
using PMS.Services.Utils.ScheduleTasks;
using PMS.Web.Factories.SystemModules;
using PMS.Web.Framework.Controllers;
using PMS.Web.Framework.Mvc.Filters;
using PMS.Web.Models.ScheduleTasks;

namespace PMS.Web.Controllers.Backend.ScheduleTasks
{
    public class ScheduleTaskManageController : BaseAdminController
    {
        #region Fields
        private readonly IScheduleTaskService _scheduleTaskService;
        private readonly ISystemModuleModleFactory _systemModuleFactory;
        #endregion

        public ScheduleTaskManageController(IScheduleTaskService scheduleTaskService,
            ISystemModuleModleFactory systemModuleFactory)
        {
            _scheduleTaskService = scheduleTaskService;
            _systemModuleFactory = systemModuleFactory;
        }

        [HttpPost]
        [IgnoreAntiforgeryToken]
        [AuthorizeCustomer(CustomerAuthorizeType.BuildInTaskUser)]
        public virtual IActionResult RunTask(string taskType)
        {
            var scheduleTask = _scheduleTaskService.GetTaskByType(taskType);
            if (scheduleTask == null)
                //schedule task cannot be loaded
                return NoContent();

            var task = new ProcessTask(scheduleTask);
            task.Execute();

            return NoContent();
        }

        [ModulePermission]
        public virtual IActionResult ScheduleTaskListView(string hashId)
        {
            int moduleId = DecodeId(hashId);
            var model = _systemModuleFactory.GetSystemModuleModel(moduleId);

            ViewBag.ModuleId = model.Id;
            ViewBag.PageTitle = model.DisplayName;
            ViewBag.BodyHtmlClass = "pear-container";
            var viewModel = new ScheduleTaskModel();
            viewModel.SetGridPageSize();
            return View(viewModel);
        }
    }
}
